import os
import shutil
import subprocess
import site
import glob
from setup_static import setup_static_resources

def find_pylibdmtx_dll():
    # 查找 pylibdmtx 的 DLL 文件
    site_packages = site.getsitepackages()[0]
    pylibdmtx_path = os.path.join(site_packages, 'pylibdmtx')
    dll_files = glob.glob(os.path.join(pylibdmtx_path, '*.dll'))
    return dll_files

def build_app():
    # 设置静态资源
    print("正在设置静态资源...")
    setup_static_resources()
    
    # 确保目录存在
    directories = ['static', 'templates', 'static/uploads']
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)

    # 查找 pylibdmtx DLL 文件
    dll_files = find_pylibdmtx_dll()
    if not dll_files:
        print("警告：未找到 pylibdmtx DLL 文件")
        # 尝试在 Python 安装目录中查找
        python_dir = os.path.dirname(os.path.dirname(os.__file__))
        dll_files = glob.glob(os.path.join(python_dir, 'Lib', 'site-packages', 'pylibdmtx', '*.dll'))
        if not dll_files:
            print("错误：无法找到必要的 DLL 文件")
            return

    print(f"找到 DLL 文件：{dll_files}")

    # 使用 PyInstaller 命令行打包
    cmd = [
        'pyinstaller',
        '--name=EquipmentManager',
        '--onefile',
        '--windowed',
        '--add-data=templates;templates',
        '--add-data=static;static',
        '--hidden-import=sqlite3',
        '--hidden-import=flask',
        '--hidden-import=werkzeug',
        '--hidden-import=pandas',
        '--hidden-import=cv2',
        '--hidden-import=pylibdmtx',
        '--hidden-import=numpy',
        '--hidden-import=requests',
        '--exclude-module=transformers',
        '--exclude-module=torch',
        '--exclude-module=tensorflow',
    ]

    # 添加 DLL 文件到打包命令
    for dll in dll_files:
        dll_name = os.path.basename(dll)
        cmd.append(f'--add-binary={dll};pylibdmtx')

    # 添加主程序
    cmd.append('run.py')
    
    subprocess.run(cmd)

    # 创建发布目录
    if not os.path.exists('release'):
        os.makedirs('release')

    # 复制必要文件到发布目录
    files_to_copy = [
        ('equipment.db', 'equipment.db'),
        ('README.txt', 'README.txt'),
    ]

    for src, dst in files_to_copy:
        if os.path.exists(src):
            shutil.copy2(src, os.path.join('release', dst))

    # 复制 DLL 文件到发布目录
    for dll in dll_files:
        dll_name = os.path.basename(dll)
        shutil.copy2(dll, os.path.join('release', dll_name))

    # 复制生成的exe到发布目录
    exe_path = os.path.join('dist', 'EquipmentManager.exe')
    if os.path.exists(exe_path):
        shutil.copy2(exe_path, os.path.join('release', 'EquipmentManager.exe'))
        print("打包完成！")
        print("发布文件已生成在: release 目录")
    else:
        print("错误：未找到生成的exe文件")

if __name__ == '__main__':
    build_app() 